package com.zhixi.exception;

import com.zhixi.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * @ClassName GlobalExceptionHandler
 * @Author zhangzhixi
 * @Description 全局异常处理器
 * @Date 2022-8-7 16:52
 * @Version 1.0
 */
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 自定义业务异常处理器-菜品及套餐分类异常类
     *
     * @param exception 异常对象
     * @return R结果对象
     */
    @ExceptionHandler(Exception.class)
    public R<String> exceptionHandler(Exception exception) {
        log.error(exception.getMessage());
        // 输出异常堆栈信息
        return R.error(exception.getMessage().substring(exception.getMessage().lastIndexOf("[") + 1, exception.getMessage().lastIndexOf("]")));
    }

    /**
     * 添加校验参数异常处理
     *
     * @param e 异常
     * @return 错误信息
     */
    @ExceptionHandler(BindException.class)
    public R<String> bindExceptionHandler(BindException e) {
        log.error("出现了异常! {}", e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return R.error(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    /**
     * 参数校验异常处理
     * @param e 异常
     * @return 错误信息
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public R<String> constraintViolationExceptionHandler(ConstraintViolationException e) {
        // 参数异常，截取：getUser.id: id不能为空
        log.error("出现了异常! {}", e.getMessage().substring(e.getMessage().lastIndexOf(":") + 1));
        return R.error(e.getMessage().substring(e.getMessage().lastIndexOf(":") + 1));
    }
}
